//
//  NSObject+Identifier.m
//  OCPopular
//
//  Created by Jarvis on 2024/5/31.
//

#import "NSObject+Identifier.h"
#import <objc/runtime.h>

@implementation NSObject (Identifier)
@dynamic identifier, superobject, subobjects;

- (NSString *)identifier {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setIdentifier:(NSString *)identifier {
    objc_setAssociatedObject(self, @selector(identifier), identifier, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSObject *)superobject {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setSuperobject:(NSObject *)superobject {
    objc_setAssociatedObject(self, @selector(superobject), superobject, OBJC_ASSOCIATION_ASSIGN);
}
- (NSMutableArray<__kindof NSObject *> *)subobjects {
    NSMutableArray *arr = objc_getAssociatedObject(self, _cmd);
    if (!arr) {
        arr = [NSMutableArray array];
        self.subobjects = arr;
    }
    return arr;
}

- (void)setSubobjects:(NSMutableArray<__kindof NSObject *> * _Nonnull)subobjects {
    objc_setAssociatedObject(self, @selector(subobjects), subobjects, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)attachObject:(NSObject *)object {
    object.superobject = self;
    [self.subobjects addObject:object];
}
- (void)detachObject:(NSObject *)object {
    [self.subobjects removeObject:object];
}

- (void)detachFromSuperObject {
    [self.superobject.subobjects removeObject:self];
}

- (NSObject *)recursionFindObject:(NSObject *)object identifier:(NSString *)identifier {
    for (NSObject *obj in object.subobjects) {
        if ([obj.identifier isEqualToString:identifier]) {
            return obj;
        } else if (obj.subobjects.count > 0) {
            return [self recursionFindObject:obj identifier:identifier];
        }
    }
    return nil;
}
- (NSObject *)findObjectByIdentifier:(NSString *)identifier {
    return [self recursionFindObject:self identifier:identifier];
}

@end
